<?php

class ProductCategoryController extends AdminController {

//    public $defaultAction='admin';
            public $model, $open_nodes;

    public function init() {
        $this->registerCssAndJs('webroot.js.fancybox', '/jquery.fancybox.pack.js', '/jquery.fancybox.css');
        Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl . '/css/client_val_form.css', 'screen');
        $this->registerAssets();
        $f = ProductCategory::model()->findAll(array('order' => 'lft'));
        $identifiers = array();
        foreach ($f as $n => $category) {
            $identifiers[] = "'" . 'node_' . $category->id . "'";
        }
        $this->open_nodes = implode(',', $identifiers);
    }

    public function actionAdmin() {
        $this->layout = '/layouts/admin';
        $dataProvider = new CActiveDataProvider('ProductCategory');
        
        Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl . '/js/plupload/plupload.full.js');
        
        $this->render('admin', array('dataProvider' => $dataProvider));
    }

    public function loadModel($id) {
        $this->model = ProductCategory::model()->findByPk($id);
        if ($this->model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
    }

    protected function returnModel($id) {
        $model = ProductCategory::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    public function printULTree_noAnchors() {
        $categories = ProductCategory::model()->findAll(array('order' => 'lft'));
        $level = 0;
        foreach ($categories as $n => $category) {
            if ($category->level == $level)
                echo CHtml::closeTag('li') . "\n";
            elseif ($category->level > $level)
                echo CHtml::openTag('ul') . "\n";
            else {
                echo CHtml::closeTag('li') . "\n";
                for ($i = $level - $category->level; $i; $i--) {
                    echo CHtml::closeTag('ul') . "\n";
                    echo CHtml::closeTag('li') . "\n";
                }
            }
            echo CHtml::openTag('li');
            echo CHtml::encode($category->name);
            $level = $category->level;
        }
        for ($i = $level; $i; $i--) {
            echo CHtml::closeTag('li') . "\n";
            echo CHtml::closeTag('ul') . "\n";
        }
    }

    public function actionFetchTree($id = 'admin') {
        parent::actionFetchTree($id);
    }

    public function actionRename() {
        $new_name = $_POST['new_name'];
        $id = $_POST['id'];
        $this->loadModel($id);
        $this->model->name = $new_name;
        $this->model->alias = MString::convertToAlias($new_name);
        if ($this->model->saveNode()) {
            echo json_encode(array('success' => true));
            Yii::app()->end();
        } else {
            echo json_encode(array('success' => false));
            Yii::app()->end();
        }
    }

    public function actionRemove() {
        $id = $_POST['id'];
        $this->loadModel($id);
        if ($this->model->deleteNode()) {
            echo json_encode(array('success' => true));
            Yii::app()->end();
        } else {
            echo json_encode(array('success' => false));
            Yii::app()->end();
        }
    }

    public function actionReturnForm() {
        $cs = Yii::app()->clientScript;
        $cs->scriptMap = array('jquery.min.js' => false, 'jquery.js' => false, 'jquery.fancybox-1.3.4.js' => false, 'jquery.jstree.js' => false, 'jquery-ui-1.8.12.custom.min.js' => false, 'json2.js' => false);
        if (isset($_POST['update_id']))
            $this->loadModel($_POST['update_id']);
        else
            $this->model = new ProductCategory;
        $this->renderPartial('_form', array('parent_id' => !empty($_POST['parent_id']) ? $_POST['parent_id'] : ''), false, true);
    }

    public function actionReturnView() {
        $cs = Yii::app()->clientScript;
        $cs->scriptMap = array('jquery.min.js' => false, 'jquery.js' => false, 'jquery.fancybox-1.3.4.js' => false, 'jquery.jstree.js' => false, 'jquery-ui-1.8.12.custom.min.js' => false, 'json2.js' => false);
        $this->loadModel($_POST['id']);
        $this->renderPartial('view', array(), false, true);
    }

    public function actionCreateRoot() {
        if (isset($_POST['ProductCategory'])) {
            $new_root = new ProductCategory;
            $new_root->attributes = $_POST['ProductCategory'];
            $new_root->alias = MString::convertToAlias($_POST['ProductCategory']['name']);
            if ($new_root->saveNode(false)) {
                echo json_encode(array('success' => true, 'id' => $new_root->primaryKey));
                Yii::app()->end();
            } else {
                echo json_encode(array('success' => false, 'message' => 'Error.Root ProductCategory was not created.'));
                Yii::app()->end();
            }
        }
    }

    public function actionCreate() {
        if (isset($_POST['ProductCategory'])) {
            $model = new ProductCategory;
            $model->attributes = $_POST['ProductCategory'];
            $model->alias = MString::convertToAlias($_POST['ProductCategory']['name']);
            $this->loadModel($_POST['parent_id']);
            if ($this->model->level == 2){
                $model->root1 = $this->model->id;
            }
            if ($model->appendTo($this->model)) {
                echo json_encode(array('success' => true, 'id' => $model->primaryKey));
                Yii::app()->end();
            } else {
                echo json_encode(array('success' => false, 'message' => 'Error.ProductCategory was not created.'));
                Yii::app()->end();
            }
        }
    }

    public function actionUpdate() {
        if (isset($_POST['ProductCategory'])) {
            $this->loadModel($_POST['update_id']);
            $this->model->attributes = $_POST['ProductCategory'];
            $this->model->alias = MString::convertToAlias($_POST['ProductCategory']['name']);
            if ($this->model->saveNode(false)) {
                echo json_encode(array('success' => true));
            }
            else
                echo json_encode(array('success' => false));
        }
    }

    public function actionMoveCopy() {
        $moved_node_id = $_POST['moved_node'];
        $new_parent_id = $_POST['new_parent'];
        $new_parent_root_id = $_POST['new_parent_root'];
        $previous_node_id = $_POST['previous_node'];
        $next_node_id = $_POST['next_node'];
        $copy = $_POST['copy'];
        $moved_node = $this->returnModel($moved_node_id);
        if ($new_parent_root_id != 'root') {
            $new_parent = $this->returnModel($new_parent_id);
            if ($previous_node_id != 'false')
                $previous_node = $this->returnModel($previous_node_id);
            if ($copy == 'false') {
                if ($previous_node_id == 'false' && $next_node_id == 'false') {
                    if ($moved_node->moveAsFirst($new_parent)) {
                        echo json_encode(array('success' => true));
                        Yii::app()->end();
                    }
                } elseif ($previous_node_id == 'false' && $next_node_id != 'false') {
                    if ($moved_node->moveAsFirst($new_parent)) {
                        echo json_encode(array('success' => true));
                        Yii::app()->end();
                    }
                } elseif ($previous_node_id != 'false' && $next_node_id == 'false') {
                    if ($moved_node->moveAsLast($new_parent)) {
                        echo json_encode(array('success' => true));
                        Yii::app()->end();
                    }
                } elseif ($previous_node_id != 'false' && $next_node_id != 'false') {
                    if ($moved_node->moveAfter($previous_node)) {
                        echo json_encode(array('success' => true));
                        Yii::app()->end();
                    }
                }
            } else {
                $copied_node = new ProductCategory;
                $copied_node->attributes = $moved_node->attributes;
                $copied_node->id = null;
                if ($copied_node->appendTo($new_parent)) {
                    echo json_encode(array('success' => true, 'id' => $copied_node->primaryKey));
                    Yii::app()->end();
                }
            }
        } else {
            if (!$moved_node->isRoot()) {
                if ($moved_node->moveAsRoot()) {
                    echo json_encode(array('success' => true));
                } else {
                    echo json_encode(array('success' => false));
                }
            } else {
                echo json_encode(array('success' => false, 'message' => 'Node is already a Root.Roots are ordered by id.'));
            }
        }
    }
    
    public function actionChooseCategory($id=null){
        $this->layout = '/layouts/main';
        $clientScript=Yii::app()->clientScript;
        $clientScript->registerCoreScript('jquery');
        
        $model=new ProductCategory;
        
        $this->render('chooseCategory', array('model'=>$model, 'id'=>$id));
    }
    
    public function actionUpload() {
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", FALSE);
        header("Pragma: no-cache");

        // Settings
        $targetDir = Yii::getPathOfAlias('webroot') . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR . date('Ymd');

        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0755, TRUE);
        }
        $cleanupTargetDir = TRUE; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds
        // 5 minutes execution time
        @set_time_limit(5 * 60);

        // Uncomment this one to fake upload time
        // usleep(5000);
        // Get parameters
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
        $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';

        // Clean the fileName for security reasons
        $fileName = preg_replace('/[^\w\._]+/', '_', $fileName);

        // Make sure the fileName is unique but only if chunking is disabled
        if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
            $ext = strrpos($fileName, '.');
            $fileName_a = substr($fileName, 0, $ext);
            $fileName_b = substr($fileName, $ext);

            $count = 1;
            while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
                $count++;

            $fileName = $fileName_a . '_' . $count . $fileName_b;
        }

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;

        // Create target dir
        if (!file_exists($targetDir))
            @mkdir($targetDir);

        // Remove old temp files
        if ($cleanupTargetDir && is_dir($targetDir) && ($dir = opendir($targetDir))) {
            while (($file = readdir($dir)) !== FALSE) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge) && ($tmpfilePath != "{$filePath}.part")) {
                    @unlink($tmpfilePath);
                }
            }

            closedir($dir);
        } else
            die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');


        // Look for the content type header
        if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
            $contentType = $_SERVER["HTTP_CONTENT_TYPE"];

        if (isset($_SERVER["CONTENT_TYPE"]))
            $contentType = $_SERVER["CONTENT_TYPE"];

        // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
        if (strpos($contentType, "multipart") !== FALSE) {
            if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
                // Open temp file
                $out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
                if ($out) {
                    // Read binary input stream and append it to temp file
                    $in = fopen($_FILES['file']['tmp_name'], "rb");

                    if ($in) {
                        while ($buff = fread($in, 4096))
                            fwrite($out, $buff);
                    } else
                        die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                    fclose($in);
                    fclose($out);
                    @unlink($_FILES['file']['tmp_name']);
                } else
                    die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            } else
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
        } else {
            // Open temp file
            $out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
            if ($out) {
                // Read binary input stream and append it to temp file
                $in = fopen("php://input", "rb");

                if ($in) {
                    while ($buff = fread($in, 4096))
                        fwrite($out, $buff);
                } else
                    die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');

                fclose($in);
                fclose($out);
            } else
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        // Check if file has been uploaded
        if (!$chunks || $chunk == $chunks - 1) {
            // Strip the temp .part suffix off
            rename("{$filePath}.part", $filePath);
            //Save o day
            $info = pathinfo($filePath);
            $fileImage = new FileImage();
            $fileImage->name = $info['filename'];
            $fileImage->url = 'upload/' . date('Ymd') . '/'. $info['basename'];
            $fileImage->createTime = time();
            $fileImage->status = 1;
            $fileImage->save();

            echo CJSON::encode(array(
                'id'=>$fileImage->id,
                'url'=>Yii::app()->baseUrl . '/' . $fileImage->url
            ));
            die;
        }
        // Return JSON-RPC response
        die('{"jsonrpc" : "2.0", "id" : null}');
    }

    protected function performAjaxValidation() {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'menu-form') {
            echo CActiveForm::validate($this->model);
            Yii::app()->end();
        }
    }

}
